// pages/audioCollection/audioCollection.js
const api = require('../../utils/api');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchParams:{},
    searchOptions: [
        { text: '按声音名搜索', value: 'name' },
        { text: '按声音类别搜索', value: 'sort' },
        { text: '按类别搜索',value: 'type'}
    ],
    selectedIndex: 0,
    audioList: null,
    pageNum:1,
    pageSize:10,
    searchType: null,
    likedAudioIds:  [],
    isLoading: false, // 是否正在加载（防止重复请求）
    hasMore: true // 是否还有更多数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const storedLikedIds = wx.getStorageSync('likedAudioIds') || [];
  
    this.setData({
      'searchParams.isLike': true, // 默认加载已收藏
      likedAudioIds: storedLikedIds // 初始化已收藏ID列表
    }, () => {
      // 确保数据设置完成后再加载音频列表
      this.loadAudiosList();
    });
  },


 
// 修改changeColor方法（切换筛选条件）
changeColor(e) {
    const index = e.currentTarget.dataset.index;
    const searchParams = {};
    if (index == 0) searchParams.isLike = true;
    if (index == 1) searchParams.isLike = false;
    
    this.setData({
      selectedIndex: index,
      searchParams: searchParams,
      pageNum: 1, // 重置页码为1
      hasMore: true, // 重置有更多数据
      audioList: null // 清空原有列表
    }, () => {
      this.loadAudiosList();
    });
  },

  loadAudiosList() {
    const { pageNum, pageSize, searchParams, isLoading, hasMore, audioList } = this.data;
  
    // 防止重复加载或无更多数据时请求
    if (isLoading || !hasMore) return;
  
    this.setData({ isLoading: true }); // 标记加载中
  
    api.audios.getAudiosListApi(pageNum, pageSize, searchParams).then(res => {
      const audioData = res.records || res.list || res || [];
      
      // 处理基础音频数据（不包含isLike状态）
      const baseAudioList = audioData.map(item => ({
        ...item,
        isPlaying: false,
        currentTime: 0,
        duration: 0,
        progress: 0,
        isLike: false // 初始默认未点赞
      }));
  
      // 第一页直接覆盖，后续页追加数据
      const mergedAudioList = pageNum === 1 
        ? baseAudioList 
        : [...(audioList || []), ...baseAudioList];
  
      // 判断是否还有更多数据（返回数据小于页大小，说明没有更多）
      const hasMoreData = audioData.length >= pageSize;
  
      // 暂存合并后的列表，再匹配点赞状态
      this.setData({ 
        audioList: mergedAudioList,
        hasMore: hasMoreData 
      }, () => {
        this.loadLikedAudios(mergedAudioList); // 匹配点赞状态
        this.setData({ isLoading: false }); // 结束加载
      });
    }).catch(err => {
      console.error('加载音频失败:', err);
      this.setData({ isLoading: false }); // 失败也要结束加载
    });
},

//查询
loadLikedAudios(audioList = []) {
    const { pageNum, pageSize } = this.data;
    const targetType = 5;
    
    api.like.getUserLikes(pageNum, pageSize, targetType).then(res => {
      console.log('获取到的已点赞资源：', res);
      const likedRecords = res.records || [];
      const likedIdsArray = likedRecords.map(item => item.id);
      const likedIdsSet = new Set(likedIdsArray);
  
      // 只更新新追加的数据的isLike状态（优化性能）
      const updatedAudioList = audioList.map(item => ({
        ...item,
        isLike: likedIdsSet.has(item.id)
      }));
  
      this.setData({ 
        audioList: updatedAudioList,
        likedAudioIds: likedIdsArray 
      }, () => {
        this.initAudioContexts(); // 初始化音频上下文
      });
    }).catch(err => {
      console.error('查询已赞音频失败：', err);
      this.initAudioContexts();
    });
},

//修改收藏状态
getLike(e) {
    const audioId = e.currentTarget.dataset.id;
    const { audioList, likedAudioIds, selectedIndex } = this.data;
    const targetType = 5;
    const audioIndex = audioList.findIndex(item => item.id === audioId);
    
    if (audioIndex === -1) return;
    
    const currentAudio = audioList[audioIndex];
    const newIsLike = !currentAudio.isLike;
    
    api.like.changeLike(audioId, newIsLike, targetType).then(res => {
      wx.showToast({
        title: newIsLike ? '点赞成功' : '取消点赞',
      });
      
      // 更新本地已赞ID和音频状态（原有逻辑不变）
      const newLikedIdsArray = [...likedAudioIds];
      if (newIsLike) {
        if (!newLikedIdsArray.includes(audioId)) {
          newLikedIdsArray.push(audioId);
        }
      } else {
        const idIndex = newLikedIdsArray.indexOf(audioId);
        if (idIndex !== -1) {
          newLikedIdsArray.splice(idIndex, 1);
        }
      }
      
      const newAudioList = [...audioList];
      newAudioList[audioIndex].isLike = newIsLike;
      
      this.setData({
        audioList: newAudioList,
        likedAudioIds: newLikedIdsArray
      }, () => {
        // 持久化存储已收藏ID
        wx.setStorageSync('likedAudioIds', newLikedIdsArray);
        
        // 原有重新加载逻辑...
        if (selectedIndex === 0 && !newIsLike) {
          this.loadAudiosList();
        }
        if (selectedIndex === 1 && newIsLike) {
          this.loadAudiosList();
        }
      });
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.data?.msg || '操作失败',
        icon: 'none',
        duration: 2000
      });
    });
},



// 初始化音频上下文
initAudioContexts() {
    const audioList = this.data.audioList.map((item, index) => {
        const audioCtx = wx.createInnerAudioContext();
        audioCtx.src = item.soundUrl;
        audioCtx.index = index;
        
        // 监听音频可以播放时获取时长
        audioCtx.onCanplay(() => {
            setTimeout(() => {
                if (audioCtx.duration) {
                    const fixedDuration = parseFloat(audioCtx.duration.toFixed(2));
                    const newAudioList = [...this.data.audioList];
                    newAudioList[index].duration = fixedDuration;
                    this.setData({ audioList: newAudioList });
                }
            }, 100);
        });
        
        // 监听播放进度更新
        audioCtx.onTimeUpdate(() => {
            const fixedCurrentTime = parseFloat(audioCtx.currentTime.toFixed(2));
            const newAudioList = [...this.data.audioList];
            newAudioList[index].currentTime = fixedCurrentTime;
            newAudioList[index].progress = fixedCurrentTime;
            this.setData({ audioList: newAudioList });
        });
        
        // 监听播放结束
        audioCtx.onEnded(() => {
            const newAudioList = [...this.data.audioList];
            newAudioList[index].isPlaying = false;
            newAudioList[index].currentTime = 0;
            newAudioList[index].progress = 0;
            this.setData({ audioList: newAudioList });
        });
        
        // 监听错误
        audioCtx.onError((error) => {
            console.error('音频播放错误:', error);
            const newAudioList = [...this.data.audioList];
            newAudioList[index].isPlaying = false;
            this.setData({ audioList: newAudioList });
        });
        
        return { ...item, audioCtx };
    });
    
    this.setData({ audioList });
},

// 切换播放/暂停
togglePlay(e) {
    const index = e.currentTarget.dataset.index;
    const newAudioList = [...this.data.audioList];
    const currentAudio = newAudioList[index];
    
    if (!currentAudio.audioCtx) return;
    
    if (currentAudio.isPlaying) {
        currentAudio.audioCtx.pause();
    } else {
        // 先暂停其他正在播放的音频
        newAudioList.forEach((item, i) => {
            if (item.isPlaying && i !== index && item.audioCtx) {
                item.audioCtx.pause();
                item.isPlaying = false;
            }
        });  
        // 播放当前音频
        currentAudio.audioCtx.play();
    }
    
    currentAudio.isPlaying = !currentAudio.isPlaying;
    this.setData({ audioList: newAudioList });
},

// 拖动进度条改变播放位置
changeProgress(e) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    const newAudioList = [...this.data.audioList];
    
    if (newAudioList[index] && newAudioList[index].audioCtx) {
        newAudioList[index].audioCtx.seek(value);
        newAudioList[index].currentTime = value;
        newAudioList[index].progress = value;
        this.setData({ audioList: newAudioList });
    }
},

// 格式化时间为 分:秒 格式
formatTime(seconds) {
    if (!seconds || isNaN(seconds)) {
        return "00:00.00";
    }
    
    const totalSeconds = Math.floor(seconds);
    const decimalPart = Math.floor((seconds - totalSeconds) * 100);
    
    const minute = Math.floor(totalSeconds / 60);
    const second = totalSeconds % 60;
    
    return `${
        minute.toString().padStart(2, '0')
    }:${
        second.toString().padStart(2, '0')
    }.${
        decimalPart.toString().padStart(2, '0')
    }`;
},

// 页面卸载时销毁音频上下文
onUnload() {
    this.data.audioList.forEach(item => {
        item.audioCtx.destroy();
    });
},

onSearchTypeChange(e) {
    this.setData({
      searchType: e.detail
    });
  },

  //输入搜索进行查询
  onInputChange(e){
    if (!this.data.searchType) {
        wx.showToast({ title: '请选择搜索关键词', icon: 'none' });
        return;
      }
      const { searchParams } = this.data;
    if(this.data.searchType == 'name'){
        searchParams.name = e.detail;
        this.loadAudiosList();
    };
    if(this.data.searchType == 'sort'){
        searchParams.sort = e.detail;
        this.loadAudiosList();
    };
    if(this.data.searchType == 'type'){
        const category = e.detail;
        switch (category){
            case '其他':
                searchParams.category = 0;
                break;
            case '人物':
                searchParams.category = 1;
                break;
            case '地理':
                searchParams.category = 2;
                break;
            case '食物':
                searchParams.category = 3;
                break;
            case '器物':
                searchParams.category = 4;
                break;
            case '事件':
                searchParams.category = 5;
                break;
            case '技艺':
                searchParams.category = 6;
                break;
            case '信俗':
                searchParams.category = 7;
                break;
            case '生物':
                searchParams.category = 8;
                break;
            case '机构':
                searchParams.category = 9;
                break;
        };
        this.loadAudiosList();
    };

    this.setData({
        searchParams: searchParams,
        pageNum: 1, // 重置页码
        hasMore: true,
        audioList: null
      }, () => {
        this.loadAudiosList();
      });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
        pageNum: 1, // 重置页码，避免分页导致数据不完整
        audioList: null
      }, () => {
        this.loadAudiosList(); // 重新加载数据
      });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore) {
        this.setData({
          pageNum: this.data.pageNum + 1
        }, () => {
          this.loadAudiosList(); // 加载下一页
        });
      }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})